package com.dt76.smallloanbackendservice.controller.etao;

import com.dt76.smallloanbackendservice.pojo.etao.CurrentUser;
import com.dt76.smallloanbackendservice.pojo.etao.Employee;
import com.dt76.smallloanbackendservice.pojo.etao.LoginLog;
import com.dt76.smallloanbackendservice.service.etao.LoginLogService;
import com.dt76.smallloanbackendservice.utils.Page;
import com.dt76.smallloanbackendservice.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @Autowired
    private LoginLogService loginLogService;

    @RequestMapping("/doEmpLogin")
    @ResponseBody
    public CurrentUser doLogin(@RequestParam String empLoginName,
                               @RequestParam String empPasswrod) {
        CurrentUser currentUser = new CurrentUser();
        UsernamePasswordToken token = new UsernamePasswordToken(empLoginName, empPasswrod);
        Subject subject = SecurityUtils.getSubject();
        Employee cEmp = new Employee();
        try {
            subject.login(token);
            cEmp = (Employee) subject.getPrincipal();
            currentUser.setLoginMsg("登录成功");
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
            currentUser.setLoginMsg("账号不存在");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            currentUser.setLoginMsg("密码错误");
        }
        currentUser.setcEmp(cEmp);
        currentUser.setAuthenticated(subject.isAuthenticated());
        System.out.println("登录---" + subject.isAuthenticated());
        return currentUser;
    }

    @RequestMapping("/addLoginMsg")
    @ResponseBody
    public Result addLoginMsg(@RequestBody LoginLog loginLog) {
        Result result = new Result();
        result.setSuccess(loginLogService.addLoginMsg(loginLog));
        return result;
    }

    @RequestMapping("/getLoginLog")
    @ResponseBody
    public Page getLogin(@RequestParam Integer pageNum,
                  @RequestParam String empName,
                  @RequestParam String startTime,
                  @RequestParam String endTime) {
        Page page = loginLogService.getLoginLog(pageNum, empName, startTime, endTime);
        return page;
    }


}
